package com.qf.dao.impl;

import com.qf.dao.GoodDao;
import com.qf.model.Goods;
import com.qf.model.GoodsType;
import com.qf.util.JDBCUtil;
import com.qf.util.PageBean;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.util.List;

public class GoodDaoImpl implements GoodDao {
    QueryRunner qr=new QueryRunner();
    @Override
    public int selectCountByTidAndLikePname(Integer tid, String pname) {
        Connection con=null;
       int a=0;
        try {
            con= JDBCUtil.getCon();
            String sql="select count(*) from product where tid=? and pname like ? and pstuts=1";
            Long b = qr.query(con,sql,new ScalarHandler<>(),tid,"%"+pname+"%");
            a= Math.toIntExact(b);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil.colseCon(con);
        }
        return a;


    }

    @Override
    public List<Goods> selectGoodsByLimit(PageBean<Goods> pageBean, Integer tid, String pname) {
        Connection con=null;
        List<Goods> list=null;
        try {
            con= JDBCUtil.getCon();
            //默认只查询上架的商品
            String sql="select * from product where tid=? and pname like ? and pstuts=1 order by pupTime limit ?,?";
            int a=(pageBean.getPageIndex()-1)*pageBean.getPageSize();
            list = qr.query(con,sql,new BeanListHandler<Goods>(Goods.class),tid,"%"+pname+"%",a,pageBean.getPageSize());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil.colseCon(con);
        }
        return list;

    }

    @Override
    public Goods selectGoodsById(Integer id) {
        Connection con=null;
       Goods good=null;
        try {
            con= JDBCUtil.getCon();
            //默认只查询上架的商品
            String sql="select * from product where pid=?";
            good = qr.query(con,sql,new BeanHandler<Goods>(Goods.class),id);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil.colseCon(con);
        }
        return good;

    }
}
